import Vue from "vue";
import axios from "axios";
import store from "@/store";
import router from "@/router";

let host = 'http://test-api.yo-bu.com';

Vue.prototype.$host = host;


// 添加请求拦截器
axios.interceptors.request.use(
	function(config) {
		return config;
	},
	function(error) {
		// 对请求错误做些什么
		return Promise.reject(error);
	}
);

// 添加响应拦截器
axios.interceptors.response.use(
	function(res) {
		let data = res.data;
		// if (data.code == 0 && data.msg == "请登录") {
		// 	alertErr(data.msg);
		// 	store.commit("clear_loginInfo"); //清除登录数据
		// 	router.push({
		// 		path: "/login"
		// 	});
		// }
		return data;
	},
	function(error) {
		alertErr('后端接口异常')
	}
);


// const chooseLanguage = Cookies.get('language') || 'zh_CN'
function api(action, data, method, uploaderConfig) {
	let reqUrl = `${host}/api/${action}`; //请求地址
	let user_id = localStorage.getItem("user_id") || "";
	let reqMethod = method ? method.toLowerCase() : "post"; //请求方式
	let token = localStorage.getItem("token") || '';
	//请求数据
	let reqData = {
		// token,
		...data,
	};
	let otherConfig = {
		headers: {
			"Content-Type": "application/json",
			"Authorization": localStorage.getItem("token"),
			"x-user-id": localStorage.getItem("user_id"),
			"App-UUID": localStorage.getItem("uuid")
		},
		transformRequest: uploaderConfig ? [] : [
			function(data) {
				if (reqMethod === "post") {
					return JSON.stringify(data);
				} else {
					let ret = "";
					for (let it in data) {
						ret += encodeURIComponent(it) + "=" + encodeURIComponent(data[it]) + "&";
					}
					return ret;
				}
			},
		],
	};

	if (reqMethod == "get") {
		return axios({
			url: reqUrl,
			method: reqMethod,
			params: reqData,
			...otherConfig,
			...uploaderConfig,
		});
	} else if (reqMethod == "post") {
		return axios({
			url: reqUrl,
			method: reqMethod,
			data: uploaderConfig ? data : reqData,
			...otherConfig,
			...uploaderConfig,
		});
	}
}
// 文件上传
function uploadApi(action, formData, params = {}) {
	let token = localStorage.getItem('token') || '';
	// if (token) {
	// 	params.token = token;
	// 	formData.append('token', token);
	// }
	return axios({
		url: `${host}/api/${action}`,
		method: 'post',
		headers: {
			"Content-Type": "application/json",
			"Authorization": localStorage.getItem("token"),
			"x-user-id": localStorage.getItem("user_id"),
			"App-UUID": localStorage.getItem("uuid")
		},
		transformRequest: [],
		data: formData,
		params
	});
}

Vue.prototype.$axios = axios;
Vue.prototype.$api = api;
Vue.prototype.$uploadApi = uploadApi;
export default {
	api,
	host,
	uploadApi
};

export {
	api,
	host,
	uploadApi
};